package com.clei.utils.io;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * ArrayList 数据容器
 *
 * @author Y
 * @date 2023-09-18
 **/
public class ArrayDataContainer<T> implements DataContainer<T> {

    /**
     * 容量
     */
    private final int capacity;

    /**
     * array
     */
    private final Object[] arr;

    /**
     * 计数器
     */
    private AtomicInteger counter;

    public ArrayDataContainer(int capacity) {
        this.capacity = capacity;
        this.arr = new Object[capacity];
        this.counter = new AtomicInteger();
    }

    /**
     * add 放入数据
     * 要支持并发写入
     *
     * @param data 数据
     * @return 添加结果 true成功 false容器满了
     */
    @Override
    public boolean add(T data) {
        int index = this.counter.getAndIncrement();
        if (index >= this.capacity) {
            return false;
        }
        this.arr[index] = data;
        return true;
    }

    /**
     * 元素量是否超过容量一半
     *
     * @return true是 false否
     */
    @Override
    public boolean overHalf() {
        return this.counter.get() * 2 > this.capacity;
    }

    /**
     * 获取容器所有数据并清空容器
     *
     * @return String list
     */
    @Override
    public List<T> getAndClear() {
        List<T> data = Arrays.stream(this.arr)
                .filter(Objects::nonNull)
                .map(o -> (T) o).collect(Collectors.toList());
        // clear
        for (int i = 0; i < this.capacity; i++) {
            this.arr[i] = null;
        }
        this.counter = new AtomicInteger();
        return data;
    }
}
